#include "Game.h"
#include "ModeGame.h"

using namespace GTL;
using namespace GTL::Engine;

inline Point TT(int t) { return Point(t%64, t/64); }

int ModeGame::Draw( float dt )
{
	Backend->ClearScreen(ColorRGBA(0,0,0,1));

	for (int x=0; x<20; x++)
	{
		for (int y=0; y<20; y++)
		{
			Point ts = TT(TheMap.Tiles[x][y].Type)*32;
			ParentGame->iTiles->Draw(Rect(ts, ts+Point(32,32)), Rect(x*32, y*32, x*32+32, y*32+32));
		}
	}

	return 0;
}

int ModeGame::Load()
{
	net = (NetworkService*)ParentGame->GetService("Network");

	for (int x=0; x<20; x++)
	{
		for (int y=0; y<20; y++)
		{
			TheMap.Tiles[x][y].Type = 605;
		}
	}

	return 0;
}

int ModeGame::Event( GameEvent event ) 
{
	if (event.EventID == Network::Event::ClientPacket)
	{
		tn_packet* packet = (tn_packet*)event.AsVoidPtr;
		
		DoServerPacket(packet);

		net->DestroyPacket(packet);
	}

	if (event.EventID == GUI::Event::Click)
	{
		if (event.SenderControl()->Name == "turn")
		{
			net->SendToServer("{type=turn}");
		}
	} 
	return 0;
}

int ModeGame::Unload()
{
	return 0;
}

int ModeGame::Update( float dt )
{
	return 0;
}

void ModeGame::DoServerPacket( tn_packet* packet )
{
	GTL::Structures::DataNodeWilson node;
	node.Parse(packet->data);
	eastl::string type = node.GetElementAsString("type", "none");
	if (type == "turn")
		Backend->LogInfo("Done turn");
}